<script setup lang="ts">
  import { addDictService, updateDictService } from '@/api/dict'
  import { TableOptions } from '@/types/dataTable'
  import { ElMessage } from 'element-plus'
  import { nextTick, reactive, ref } from 'vue'
  import { Bell, Search, Delete, Edit, Plus, CaretRight } from '@element-plus/icons-vue'
  import { useDictForm } from './hooks/useDictItems'
  import { useParamsListQuery } from '@/hooks/paramsListQuery'
  import SysDicValue from './components/value.vue'
  import { DictItem } from '@/types/dict'
  const pagingTable = ref()
  const tempLabelSelects = ref<Record<string, string>>({}) // 为每个字典项创建独立的选择状态
  const activeTreeSelects = ref<Record<string, boolean>>({}) // 控制哪些 TreeSelect 组件被激活
  const { dialogConfig, DictForm, rules, setAddMode, refForm, resetForm, setEditMode } = useDictForm()
  const { listQuery } = useParamsListQuery()

  // 获取或初始化特定字典项的选择值
  const getTempLabelSelect = (dictCode: string) => {
    if (!tempLabelSelects.value[dictCode]) {
      tempLabelSelects.value[dictCode] = ''
    }
    return tempLabelSelects.value[dictCode]
  }

  // 设置特定字典项的选择值
  const setTempLabelSelect = (dictCode: string, value: string) => {
    tempLabelSelects.value[dictCode] = value || null
  }

  // 激活 TreeSelect 组件
  const activateTreeSelect = (dictCode: string) => {
    activeTreeSelects.value[dictCode] = true
  }

  // 检查 TreeSelect 是否已激活
  const isTreeSelectActive = (dictCode: string) => {
    return activeTreeSelects.value[dictCode] || false
  }
  const options = reactive<TableOptions>({
    add: {
      enable: true,
      permission: '',
    },
    edit: {
      enable: true,
      permission: '',
    },
    delete: {
      enable: true,
      permission: '',
      url: '/dict/deleteDicData',
    },
    listUrl: '/dict/getDicDataAll', // 列表请求URL
  })
  const isVisible = ref(false)
  const isVisibleDrawer = ref(false)
  const postDict = ref<Partial<DictItem>>({}) // 当前维护的字典数据
  // 打开字典添加框
  const addDicDialog = () => {
    isVisible.value = true
    setAddMode()
  }
  // 打开字典编辑框
  const editDicDialog = (id: number, item: any) => {
    isVisible.value = true
    setEditMode(item)
  }
  // 弹框回调函数处理
  const handleDialogToggle = (val: boolean) => {
    isVisible.value = val
  }
  const submitDialog = () => {
    refForm.value?.validate(async (valid) => {
      if (valid) {
        if (DictForm.value.id !== null && DictForm.value.id !== '') {
          await updateDictService(DictForm.value)
          ElMessage.success('字典信息更新成功')
        } else {
          await addDictService(DictForm.value)
          ElMessage.success('字典添加成功')
        }
        pagingTable.value?.getList()
        isVisible.value = false
        resetForm()
      }
    })
  }
  // 操作字典项
  const showCatalog = (val) => {
    console.log('showCatalog called with val:', val)
    isVisibleDrawer.value = true
    postDict.value = { ...val, name: '当前字典项：' + val.name }
  }
</script>
<template>
  <div class="app-container">
    <data-table ref="pagingTable" v-model:list-query="listQuery" :options="options" @add="addDicDialog" @edit="editDicDialog">
      <template #filter-content>
        <el-input
          id="search-keyword"
          v-model.trim="listQuery.params.keyword"
          :prefix-icon="Search"
          style="width: 200px"
          placeholder="名称/编码"
          class="filter-item"
        />
      </template>
      <template #tip-content>
        <div class="tip">
          <el-icon style="margin-right: 8px; font-size: 16px"><Bell /></el-icon>
          <span>字典分类删除需要前后端统一，谨慎删除！</span>
        </div>
      </template>
      <template #data-columns>
        <el-table-column type="selection" width="55" />
        <el-table-column show-overflow-tooltip align="center" label="名称" prop="name">
          <template #default="scope">
            <DetailLink :title="scope.row.name" permission="" @click="editDicDialog(scope.row.id, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip align="center" label="编码" prop="dictCode" />
        <el-table-column show-overflow-tooltip align="center" label="分类">
          <template #default="scope">
            <el-tag v-if="scope.row.type.includes('数据')" type="primary">{{ scope.row.type }}</el-tag>
            <el-tag v-else type="success">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip align="center" label="描述" prop="desc" />
        <el-table-column align="center" label="预览">
          <template #default="scope">
            <!-- 未激活状态：显示蒙层/占位符 -->
            <div
              v-if="!isTreeSelectActive(scope.row.dictCode)"
              class="tree-select-placeholder"
              @click="activateTreeSelect(scope.row.dictCode)"
            >
              <el-icon class="placeholder-icon"><CaretRight /></el-icon>
              <span class="placeholder-text">点击预览</span>
            </div>

            <!-- 激活状态：显示真实的 TreeSelect 组件 -->
            <tree-select
              v-else
              :model-value="getTempLabelSelect(scope.row.dictCode)"
              :dic-code="scope.row.dictCode"
              @update:model-value="(value) => setTempLabelSelect(scope.row.dictCode, value)"
            ></tree-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="配置">
          <template #default="scope">
            <el-link v-permission="['']" class="tool" type="primary" size="small" @click="showCatalog(scope.row)">
              <el-icon style="margin-right: 8px"><Tools /></el-icon>字典项</el-link
            >
          </template>
        </el-table-column>
      </template>
    </data-table>
  </div>
  <!-- 弹框 -->
  <dia-log v-model:visible="isVisible" :dialog-config="dialogConfig" @cancellation="handleDialogToggle" @save="submitDialog">
    <template #content>
      <el-form ref="refForm" :model="DictForm" :rules="rules" label-width="70px" class="justify-label" status-icon>
        <el-form-item label="名称" prop="name">
          <el-input id="dict-name" v-model="DictForm.name" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <div class="dialog-item">
            <el-radio-group id="dict-type" v-model="DictForm.type">
              <el-radio value="分类字典" size="large">分类字典</el-radio>
              <el-radio value="数据字典" size="large">数据字典</el-radio>
            </el-radio-group>
            <div class="dialog-alert">
              <el-icon><InfoFilled /></el-icon>
              <div>通用下拉框推荐分类，状态审批推荐数据</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="编码" prop="dictCode">
          <el-input
            id="dict-code"
            v-model="DictForm.dictCode"
            :disabled="DictForm.id !== '' && DictForm.id !== null"
            placeholder="请输入字典编码"
          />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input id="dict-desc" v-model="DictForm.desc" type="textarea" placeholder="请输入字典描述" />
        </el-form-item>
      </el-form>
    </template>
    <template #tip>
      <div class="dialog-alert">
        <el-icon><WarnTriangleFilled /></el-icon>
        <span>字典编码应该设置成唯一值，且设置后不可修改</span>
      </div>
    </template>
  </dia-log>
  <!-- 右侧字典项 -->
  <sys-dic-value v-model:visible="isVisibleDrawer" :post-form="postDict"></sys-dic-value>
</template>
<style lang="scss" scoped>
  .tip {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 4px 16px;
    background-color: #fef0f0;
    border: 1px solid #fde2e2;
    border-radius: 4px;
    color: #f56c6c;
  }
  .tree-select-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 4px 6px;
    background: #f5f7fa;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    color: #909399;
    &:hover {
      background: #ecf5ff;
      border-color: #409eff;
      color: #409eff;
      .placeholder-icon {
        transform: translateX(2px);
      }
    }

    .placeholder-icon {
      margin-right: 6px;
      font-size: 14px;
      transition: transform 0.2s ease;
    }

    .placeholder-text {
      font-size: 12px;
      user-select: none;
    }
  }
</style>
